﻿namespace ExcelToTPI
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Data;
    using System.IO;
    using System.Windows.Forms;

    using ExcelToTPI.Class;

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;

    using TPI;
    using NLog;

    public partial class DeleteNoDOI : Form
    {
        public Client NewClient = new Client();                     // 定义连接句柄
        public string dbCode = string.Empty;                        // 数据库代码
        private delegate void RecordNoDoiDelegate(string message);          // 记录无数字对象的记录
        private delegate void ReportProcessedCountDelegate(string message); // 报告已处理记录数
        public DeleteNoDOI()
        {
            this.InitializeComponent();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// 检测数据库连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        #region 检测数据库连接
        private void Button_ConnectServer_Click(object sender, EventArgs e)
        {
            int nServerPort = 0;
            try
            {
                nServerPort = Convert.ToInt32(this.TextBox_ServerPort.Text.Trim());
            }
            catch
            {
                MessageBox.Show("端口号必须为数字");

                return;
            }

            if (this.CheckServerConnect(this.TextBox_ServerIP.Text.Trim(), nServerPort, this.TextBox_ServerUserName.Text.Trim(), this.TextBox_ServerPsw.Text.Trim()))
            {
                MessageBox.Show("连接服务器成功！");
            }
            else
            {
                MessageBox.Show("连接服务器失败，请重新配置");

                this.TextBox_ServerIP.Focus();

                return;
            }

            //绑定数据库列表
            this.BindDataBaseList();
        }
        #endregion

        /// <summary>
        /// 数据库连接
        /// </summary>
        /// <param name="strServerIP">
        /// </param>
        /// <param name="nServerPort">
        /// The n Server Port.
        /// </param>
        /// <param name="strServerUserName">
        /// </param>
        /// <param name="strServerPsw">
        /// </param>
        /// <returns>
        /// </returns>
        private bool CheckServerConnect(string strServerIP, int nServerPort, string strServerUserName, string strServerPsw)
        {
            if (this.NewClient.Connect(strServerIP, nServerPort, strServerUserName, strServerPsw))
            {
                this.NewClient.Close();

                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 建立数据库连接
        /// </summary>
        /// <returns>
        /// </returns>
        private bool ConnectServer()
        {
            if (this.NewClient.Connect(this.TextBox_ServerIP.Text.Trim(), Convert.ToInt32(this.TextBox_ServerPort.Text.Trim()), this.TextBox_ServerUserName.Text.Trim(), this.TextBox_ServerPsw.Text.Trim()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 关闭数据库连接
        /// </summary>
        private void CloseServerConnect()
        {
            if (this.NewClient.IsConnected())
            {
                this.NewClient.Close();
            }
        }

        /// <summary>
        /// 计算文件MD5值
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        #region 计算文件MD5值
        public static string FileToMD5(string path)
        {
            try
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open))
                {
                    System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                    byte[] b = md5.ComputeHash(fs);
                    return System.BitConverter.ToString(b).Replace("-", "");
                }
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }
        #endregion

        /// <summary>
        /// 绑定数据库列表
        /// </summary>
        #region 绑定数据库列表
        private void BindDataBaseList()
        {
            if (!this.NewClient.IsConnected())
            {
                if (!this.ConnectServer())
                {
                    MessageBox.Show("无法连接数据库，请重新配置。");

                    return;
                }
            }

            string strSql = "select * from sys_cms_database";

            DataTable DT = TPIHelper.GetDataSet_Datatable(this.NewClient, strSql);

            if (DT != null && DT.Rows.Count > 0)
            {
                this.cbDBList.DataSource = DT;
                this.cbDBList.ValueMember = "DATABASECODE";
                this.cbDBList.DisplayMember = "DATABASENAME";
            }
        }
        #endregion

        /// <summary>
        /// 数据库列表选中发生改变的处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        #region 数据库列表选中发生改变的处理
        private void ComboBox_DBList_SelectedIndexChanged(object sender, EventArgs e)
        {
            dbCode = cbDBList.SelectedValue as string;
            this.rtbMessage.Text = string.Empty;
            if (dbCode != null)
            {
                string strSql = string.Format("select * from {0}_Metadata order by sys_fld_sysid asc", dbCode);
                int iRecordCount = TPIHelper.GetDataCount(NewClient, strSql);
                lbTotal.Text = string.Format("记录总数：{0}条", iRecordCount);
                lbProcessed.Text = "已处理0条记录";
            }
        }
        #endregion

        /// <summary>
        /// 开始对应的处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_StartRelate_Click(object sender, EventArgs e)
        {
            try
            {
                this.rtbMessage.Text = string.Empty;
                if (backgroundWorker1.IsBusy != true)
                {
                    // Start the asynchronous operation.
                    backgroundWorker1.RunWorkerAsync();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除无数字对象记录发生异常 异常信息：" + ex.Message + " 堆栈信息：" + ex.StackTrace);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.WorkerSupportsCancellation)
            {
                // Cancel the asynchronous operation.
                backgroundWorker1.CancelAsync();
            }
        }

        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            try
            {
                if (!this.NewClient.IsConnected())
                {
                    if (!this.ConnectServer())
                    {
                        MessageBox.Show("无法连接数据库，请重新配置。");
                        return;
                    }
                }
                int iProcessCount = 0;  // 已处理记录数
                int iDeletedCount = 0;  // 已删除记录数
                string strSql = string.Format("select * from {0}_MetaData order by sys_fld_sysid asc", dbCode);
                RecordSet rs = this.NewClient.OpenRecordSet(strSql);
                int iRecordCount = rs.GetCount();
                rs.MoveFirst();
                while (!rs.IsEOF())
                {
                    string sysid = rs.GetValue("sys_fld_sysid");
                    strSql = string.Format("select * from {0}_MetaData_File where RecordId={1}", dbCode, sysid);
                    int iFileCount = TPIHelper.GetDataCount(this.NewClient, strSql);
                    if (iFileCount <= 0)
                    {
                        // 构造删除
                        strSql = string.Format("delete from {0}_MetaData where sys_fld_sysid={1}", dbCode, sysid);
                        // 记录已删除的记录
                        TPIHelper.ExecSql(this.NewClient, strSql);
                        LogManager.GetCurrentClassLogger().Trace(strSql);
                        this.RecordNoDoi(strSql);
                        iDeletedCount++;
                    }
                    iProcessCount++;
                    int percentComplete = (int)((float)iProcessCount / (float)iRecordCount * 100);
                    worker.ReportProgress(percentComplete);
                    this.ReportProcessedCount(string.Format("已处理{0}条记录，已删除{1}条记录", iProcessCount, iDeletedCount));
                    rs.MoveNext();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导入Excel发生异常 异常信息：" + ex.Message + " 堆栈信息：" + ex.StackTrace);
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.ProgressBar1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("数据处理完成！");
        }

        private void DeleteNoDOI_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.CloseServerConnect();
            this.Owner.Show();
        }

        /// <summary>
        /// 记录无数字对象的数据
        /// </summary>
        /// <param name="message"></param>
        private void RecordNoDoi(string message)
        {
            if (this.rtbMessage.InvokeRequired)     //等待异步
            {
                RecordNoDoiDelegate rnDelegate = new RecordNoDoiDelegate(RecordNoDoi);
                this.Invoke(rnDelegate, message);   //通过代理调用刷新方法
            }
            else
            {
                this.rtbMessage.Text += message + "\r\n";
            }
        }

        /// <summary>
        /// 报告已处理的记录数
        /// </summary>
        /// <param name="message"></param>
        private void ReportProcessedCount(string message)
        {
            if (this.lbProcessed.InvokeRequired)     //等待异步
            {
                ReportProcessedCountDelegate rpcDelegate = new ReportProcessedCountDelegate(ReportProcessedCount);
                this.Invoke(rpcDelegate, message);   //通过代理调用刷新方法
            }
            else
            {
                this.lbProcessed.Text = message;
            }
        }
    }
}